let serverHideTimeout = null, serverHideDelay = 100;
var vue = new Vue({
	el: "#app", 
	data: {
		imgUrls: [],
		nav: [],
		project_nav: [],
		project_list: [],
		imgUrl: "https://app.meijiangzi.com/static/",
		scroll_top: 0,
		main_adv: "",
		adv2: "",
		adv3: "",
		adv4: "",
		adv5: "",
		advs: "",
		province_name: "陕西省",
		province_id: 61,
		isbottom: !1,
		latitude: "34.347269",
		longitude: "108.94704",
		page: 1,
		alpha: 0,
		show_model: !1,
		has_msg: !1,
		activity_arr: [],
		translate:0,
		picWidth:750, 
		isExcute: false, 
		ver: null 
	}, 

	methods: {
		getBanner: function() {
			var t = this;
			wx.showLoading({
				title: "加载中",
				mask: !0
			});
			// 首页获取轮播图 
			this.$http.post(baseUrl+"/banner/query", {
				type:"sy"
			}).then(function(a) {
				wx.hideLoading();
				var s = a.data;
				if (!s.success) return wx.showToast({
					title: s.description,
					icon: "none",
					duration: 2e3,
					mask: !1
				}), !1;
				t.imgUrls = s.data;
				t.imgUrls.forEach(function (e) {
				  e.type = 6;
				});
				this.bannersRock(true);
			}).catch(function(t) {
				wx.hideLoading(), wx.showToast({
					title: "网络错误，请检查网络",
					icon: "none",
					duration: 2e3,
					mask: !1
				});
			});
		},
		getNav: function() {
			var t = this;
			wx.showLoading({
				title: "加载中",
				mask: !0
			}), this.$http.post(baseUrl+"api/project/nav", {
				position: 1,
				page: 1,
				pageSize: 5
			}).then(function(a) {
				wx.hideLoading();
				var s = a.data;
				if (!s.success) return wx.showToast({
					title: s.description,
					icon: "none",
					duration: 2e3,
					mask: !0
				}), !1;
				t.nav = s.data;
				t.nav.forEach(function (e) {
					if(e.name=='品质医美'){
						e.type = 5;
					}else if(e.name == '积分商城'){
						e.type = 7;
					}else if(e.name == '共享名医'){
						e.type = 14;
					}else if(e.name == '医美院库'){
						e.type = 13;
					}else if(e.name == '医美百科'){
						e.type = 12;
					}
				  });
			}).catch(function(t) {
				wx.hideLoading(), wx.showToast({
					title: "网络错误，请检查网络",
					icon: "none",
					duration: 2e3,
					mask: !0
				});
			});
		},
		search: function() {
			Jump.to(page.search.searchAllPage);
		},
		getProjectNav: function() {
			var t = this;
			wx.showLoading({
				title: "加载中",
				mask: !0
			}), this.$http.post(baseUrl+"api/project/projectNav").then(function(a) {
				wx.hideLoading();
				var s = a.data;
			  if (!s.success) return wx.showToast({
				title: s.description,
					icon: "none",
					duration: 2e3,
					mask: !0
				}), !1;
				t.project_nav = s.data;
				t.project_nav.forEach(function (e) {
					e.type = 1;
				  });
			}).catch(function(t) {
				wx.hideLoading(), wx.showToast({
					title: "网络错误，请检查网络",
					icon: "none",
					duration: 2e3,
					mask: !0
				});
			});
		},
		getadv: function() {},
		getprojectList: function(isShowLoading) {
			var t = this;
			if (this.isbottom) return !1;
			if(isShowLoading){
				wx.showLoading({
					title: "加载中",
					mask: !0
				});
			}
			var a = this, s = void 0;
			s = "" != this.province_id ? {
			  currentPage: this.page,
				pageSize: 10,
				//zoneCode: this.province_id,
				lat: this.latitude,
				lng: this.longitude
			} : {
				currentPage: this.page,
				pageSize: 10,
				lat: this.latitude,
				lng: this.longitude
			}, setTimeout(function() {
			  t.$http.post(baseUrl+"api/project/list", s).then(function(s) {
				  if(isShowLoading){
					  wx.hideLoading();
				  }
					var i = s.data;
					if (!i.success) return wx.showToast({
					  title: '加载失败:' + i.description,
						icon: "none",
						duration: 2e3,
						mask: !0
					}), !1;
					var e;
					if (0 == i.data.length && t.page > 1) return wx.showToast({
						title: "已经到最底下了",
						icon: "none",
						duration: 1e3,
						mask: !0
					}), t.isbottom = !0, !1;
					this.isExcute = false; 
					i.data.forEach(function (e) {
					  e.type = 11;
					});
					(e = a.project_list).push.apply(e, i.data);
				}).catch(function(t) {
					isShowLoading && wx.hideLoading(), console.log(t), wx.showToast({
						title: "网络错误，请检查网络",
						icon: "none",
						duration: 2e3,
						mask: !0
					});
				});
			}, 200);
		},
		bannersRock:function(init){
			var t = this;
			if(init){
				t.left = new Array();
				var banners = this.imgUrls;
				banners.forEach(function(e,index){
					if(index==banners.length-1){
						return;
					}
					t.left.push((index+1)*t.picWidth*-1);
				});
				t.right = new Array();
				t.flag = true;
				
			}
			t.inter = setInterval(function(){
				if(t.flag){
					t.translate = t.left.shift();
					t.right.push(t.translate);
					if(t.left.length==0){
						t.flag =false;
					}
				}else{
					var translate = t.right.pop();
					t.translate = translate+t.picWidth;
					t.left.push(translate);
					if(t.right.length==0){
						t.flag = true;
						t.left.reverse();
					}
				}
			},2000)
			
		},
		scroll: function(t) {
			var a = t.mp.detail.scrollTop;
			this.alpha = a / 200 > 1 ? 1 : a / 200;
		},
		selectAddress: function() {
	//                     wx.navigateTo({
	//                         url: "/pages/select_city_new/main"
	//                     });
		},
		loadCity: function() {
			var t = this;
			if(wx.getStorageSync("province_info")){
				return; 
			}
			try{
				$.ajax({
					url: "https://api.map.baidu.com/geocoder/v2/?ak=itcGzLG0IrFlBPQlTFCxytDB10fwNdag&location=" + t.latitude + "," + t.longitude + "&output=json",
					type: "get", 
					dataType:'jsonp',
					data: {}
				}).done(function(a){
					setTimeout(function() {
						var prov = a.result.addressComponent.province, prov_id = a.result.addressComponent.adcode;
						t.province_name = prov, t.province_id = prov_id.substr(0, 2); 
						wx.setStorageSync("province_info", JSON.stringify({
						  province_name: prov,
						  province_id: prov_id.substr(0, 2)
						}));
						t.project_list = [];
						t.getprojectList(false);
					}, 10);
				})
				.fail(function(b) {
					console.log('地址解析失败');
				});
			} catch (e){
				console.log('地址解析出错:'+e);
			}
		},
		toSelectCity: function(){
			Jump.to(page.index.city);
		},
		search_focus: function() {
			Jump.to(page.index.search);
		},
		get_location: function() {
			var t = this;
			try{
				plus.geolocation.getCurrentPosition(function(p){
					t.longitude = p.coords.longitude, t.latitude = p.coords.latitude;
					if(t.longitude > 1){
						//定位成功
						t.loadCity();
						wx.setStorageSync("userLng", t.longitude), wx.setStorageSync("userLat", t.latitude);
					}else{
						console.log('定位失败:' + t.longitude + ', ' + t.latitude);
					}
				}, function(e){
					t.province_name = "陕西省", t.province_id = 61;
				},{provider: 'baidu', geocode: true});
			}catch(e){
				t.province_name = "陕西省", t.province_id = 61;
				console.log(e);
			}
			/*if(navigator.geolocation) {
				navigator.geolocation.getCurrentPosition(function(){
					t.longitude = position.coords.longitude, t.latitude = position.coords.latitude, t.loadCity();
					wx.setStorageSync("userLng", t.longitude), wx.setStorageSync("userLat", t.latitude);
				},function(error){
					let errorMsg = '无法获取地理位置'; 
					switch(error.code) {
						case error.PERMISSION_DENIED:
							errorMsg = "定位失败,用户拒绝请求地理定位";
							break;
						case error.POSITION_UNAVAILABLE:
							errorMsg = "定位失败,位置信息是不可用";
							break;
						case error.TIMEOUT:
							errorMsg = "定位失败,请求获取用户位置超时";
							break;
						case error.UNKNOWN_ERROR:
							errorMsg = "定位失败,定位系统失效";
							break;
					}
					console.log(errorMsg);
					t.province_name = "陕西省", t.province_id = 61;
				},{
					enableHighAcuracy : true,// 指示浏览器获取高精度的位置，默认为false  
					timeout : 5000,// 指定获取地理位置的超时时间，默认不限时，单位为毫秒  
					maximumAge : 30 * 60 * 1000 // 最长有效期，在重复获取地理位置时，此参数指定多久再次获取位置。  
				});
			}else{
				wx.showToast({
					title: "无法获取地理位置",
					icon: "none",
					duration: 2e3,
					mask: !0
				}), t.province_name = "陕西省", t.province_id = 61;
			}*/
		},
		select_nav: function(t) {
			switch (t.name) {
			  case "品质医美":
	//                         wx.redirectTo({
	//                             url: "/pages/index/main?path=mall"
	//                         });
				break;

			  case "积分商城":
	//                         wx.redirectTo({
	//                             url: "/pages/index/main?path=integralMall"
	//                         });
				break;

			  default:
				wx.showToast({
					title: "敬请期待！",
					icon: "none",
					duration: 2e3,
					mask: !0,
					success: function(t) {}
				});
			}
		},
		check_gift: function() {},
		close: function() {
			this.show_model = !1;
		},
		to_detail: function(t) {
			switch (t.type - 0) {
			  case 1:
				Jump.to(page.index.list, "typeId=" + t.typeId + "&name=" + t.name);
				break;
			  case 5:
				wx.showToast({
					title: "芯悦美肤对接中,敬请期待",
					icon: "none",
					duration: 2e3,
					mask: !1
				});
				break;
			  case 6:
				const businessType = t.businessType; 
				if(businessType && businessType == 'activity'){
					Jump.to(page.activity.index, "id=" + t.businessId);
				}else{
					Jump.to(page.index.detail, "id=" + t.businessId);
				}
				break;
			  case 7:
				Jump.to(page.product.index);
				break;
			  case 11: 
				Jump.to(page.index.detail, "id=" + t.guid+"&salt="+t.orderCount);
				break;
			  case 12: 
				Jump.to(page.hospital.baike);
				break;
			  case 13: 
				Jump.to(page.hospital.hospital);
				break;
			  case 14: 
				Jump.to(page.hospital.doctor);
				break;
			  default:
				wx.hideLoading();
				wx.showToast({
					title: "敬请期待",
					icon: "none",
					duration: 2e3,
					mask: !1
				});
			}
		},
		handleScroll: function(){
			const that = this; 
			if(serverHideTimeout != null){
				that.hideServerOnScroll();
				clearTimeout(serverHideTimeout);
			}
			serverHideTimeout = setTimeout(that.showServerAfterScroll, serverHideDelay);
			// 防止重复
			if (this.isExcute) {
				return;
			}
			if (this.isbottom) {
				return;
			}
			var flag = srollEvent.isReachBottom();
			if (!flag) {
				return;
			}
			this.isExcute = true;
			//页码+1
			this.page++;
			this.getprojectList(true);
		},
		hideServerOnScroll: function(){
			document.getElementById('serverBtn').style.right = '-50px';
		},
		showServerAfterScroll: function(){
			document.getElementById('serverBtn').style.right = '15px';
		},
		touchStart: function(ev) {
			ev = ev || event;
			ev.preventDefault();
			//                      console.log(ev.targetTouches);
			//                      console.log(ev.changedTouches);
			if (ev.touches.length == 1) { //tounches类数组，等于1时表示此时有只有一只手指在触摸屏幕
				this.startX = ev.touches[0].clientX; // 记录开始位置
			}
		},
		touchEnd: function(ev, e,index) {
			ev = ev || event;
			ev.preventDefault();
			if (ev.changedTouches.length == 1) {
				var endX = ev.changedTouches[0].clientX;
				this.disX = endX - this.startX;
				if (this.disX < 0) {
					// 左滑
					if(index==this.imgUrls.length-1){
						return;
					}else{
						clearInterval(this.inter)
						this.translate = this.translate-this.picWidth;
						this.bannersRock(false);
					}
				} else if(this.disX >0) {
					// 右滑
					if(index==0){
						return;
					}else{
						clearInterval(this.inter)
						this.translate = this.translate+this.picWidth;
						this.bannersRock(false);
					}
				}else{
					this.to_detail(e);
				}
			}
		},
		goToAd: function(){
			alert(1);
		},
		getVersion: function(){
			const that = this;
			this.$http.post("https://app.meijiangzi.com/api/app/version", {})
			.then(function(a) {
				that.ver = a.data;
				that.updateApp();
			}).catch(function(t) {
				console.log('Get app version failed: ', t);
			});
		}, 
		updateApp: function(){
			const that = this; 
			const storageVer = localStorage.getItem('storageVer'), remoteVer = that.ver;
			if(storageVer && storageVer == remoteVer){
				//用户忽略本次更新
				console.log('User ignore this version: '+remoteVer);
			}else{
				//用户没忽略本次更新
				document.addEventListener('plusready', function(){
					// 获取本地应用资源版本号  
					plus.runtime.getProperty(plus.runtime.appid, function(inf){  
						//wgtVer=inf.version;  
						const locaVer = plus.runtime.version, remoteVer = that.ver;
						// console.log("remote ver: " + remoteVer + "，当前应用版本："+inf.version+"---"+locaVer); 
						if(remoteVer && remoteVer != locaVer){
							plus.nativeUI.confirm('发现新版本，是否立即更新？', function(event){
								const op = event.index;
								//设置本次更新标记
								localStorage.setItem('storageVer', remoteVer);
								if(op == 0){
									//开始更新
									const os = plus.os.name; 
									let appUrl;
									if(/^IOS$/i.test(os)){
										//ios
										appUrl='itms-apps://itunes.apple.com/cn/app/id1459124277?mt=8'; 
										plus.runtime.openURL(appUrl);  
									}else{
										//android
										plus.nativeUI.showWaiting("下载更新");
										appUrl = 'https://mjz.yitavc.com/static/mjzapp.apk';
										plus.downloader.createDownload( appUrl , {filename:"_doc/update/"}, function(d,status){
											if ( status == 200 ) { 
												console.log("下载更新成功："+d.filename);
												plus.runtime.install(d.filename,{},function(){
													plus.nativeUI.closeWaiting();
													console.log("安装更新成功！");
													plus.nativeUI.alert("更新完成！",function(){
														// 更新完成后重启应用
														plus.runtime.restart();
													});
												},function(e){
													plus.nativeUI.closeWaiting();
													console.log("安装更新失败！["+e.code+"]："+e.message);
													plus.nativeUI.toast("安装更新失败！");
												});
											} else {
												console.log("下载更新失败！");
												plus.nativeUI.toast("下载更新失败！");
											}
											plus.nativeUI.closeWaiting();
										}).start();
									}
								}
							});
						}
					});
				});
			}
		}, 
		initKF: function(){
			try{
				(function(m, ei, q, i, a, j, s) {
					m[i] = m[i] || function() {
						(m[i].a = m[i].a || []).push(arguments)
					};
					j = ei.createElement(q),
						s = ei.getElementsByTagName(q)[0];
					j.async = true;
					j.charset = 'UTF-8';
					j.src = 'https://static.meiqia.com/dist/meiqia.js?_=t';
					s.parentNode.insertBefore(j, s);
				})(window, document, 'script', '_MEIQIA');
				_MEIQIA('entId', '147884');
				// 在这里开启无按钮模式（常规情况下，需要紧跟在美洽嵌入代码之后）
				_MEIQIA('withoutBtn');
			}catch(e){
				//TODO handle the exception
				console.log('加载美洽客服失败:'+JSON.stringify(e));
			}
		}, 
		openServer: function(){
			// try{
			// 	_MEIQIA('showPanel');
			// }catch(e){
			// 	//TODO handle the exception
			// 	wx.showToast({
			// 		title: "打开在线客服失败，请稍后再试",
			// 		icon: "none",
			// 		duration: 2e3,
			// 		mask: !0
			// 	});
			// }
			Jump.to(page.mine.onlineService);
		}
	},
	mounted: function() {
		window.addEventListener("scroll", this.handleScroll, {
			passive: false
		});
		this.getVersion();
		// const isReadNewAd = wx.getStorageSync('isReadNewAd'); 要一直弹出
		// if(!isReadNewAd){
			const adImg = $('<image id="newerAdImg" src="../../images/index/ad-index.png"/>');
			$(document).dialog({
				titleShow: false, 
				closeBtnShow: true, 
				dialogClass: 'ad-dialog', 
				content: adImg[0],
				buttonTextConfirm: '',
				onClosed: function(){
					wx.setStorageSync('isReadNewAd', '1');
				}
			});
		// };
	},
	created: function() {
		var t = this; 
		this.picWidth = window.screen.width*2;
		this.getBanner(), /*this.getNav(),*/ this.getProjectNav(), t.getprojectList(true), wx.getStorage({
			key: "province_info",
			success: function(a) {
				var s = JSON.parse(a.data);
				t.province_name = s.province_name, t.province_id = s.province_id, t.getprojectList(true);
			},
			fail: function() {
				console.log('获取省份信息失败');
			}
		});
		// this.initKF();
	}
});

document.addEventListener('plusready', function(){
	vue.get_location();
});